/*
 * Created on 25.06.2006 by leck
 *
 */
package de.devisnik.eidle.picture;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;

import de.devisnik.eidle.AbstractScreenToggler;
import de.devisnik.eidle.ScreenHandler;
import de.devisnik.eidle.screen.IScreen;
import de.devisnik.eidle.screen.IScreenListener;
import de.devisnik.eidle.util.AbstractScreen;

public abstract class MultiImageScreen extends AbstractScreen {

	private AbstractScreenToggler itsScreenToggler;

	private Listener itsPageDownListener;

	private Display itsDisplay;

	public MultiImageScreen(final String name) {
		super(name);
	}

	public abstract ImageDescriptor[] createImageDescriptors();

	public void createControl(final Composite parent) {
		itsDisplay = parent.getDisplay();
		final ImageDescriptor[] descriptors = createImageDescriptors();
		final IScreen[] screens = new IScreen[descriptors.length];
		for (int i = 0; i < screens.length; i++) {
			screens[i] = createPictureScreen(parent, descriptors[i]);
		}
		itsScreenToggler = createScreenToggler(parent, screens);
		itsScreenToggler.nextScreen();

		addKeyListener(parent.getDisplay());
	}

	private void addKeyListener(final Display display) {
		itsPageDownListener = new Listener() {

			public void handleEvent(final Event event) {
				if (event.keyCode == SWT.PAGE_DOWN) { // Page down pressed
					itsScreenToggler.nextScreen();
				}
				if (event.keyCode == SWT.PAGE_UP) { // Page up pressed
					itsScreenToggler.previousScreen();
				}
			}
		};
		display.addFilter(SWT.KeyDown, itsPageDownListener);
	}

	private void removeKeyListener(final Display display) {
		display.removeFilter(SWT.KeyDown, itsPageDownListener);
	}

	private AbstractScreenToggler createScreenToggler(final Composite parent,
			final IScreen[] screens) {
		final ScreenHandler screenHandler = new ScreenHandler(parent);
		final AbstractScreenToggler screenToggler = new AbstractScreenToggler(
				screens, screenHandler) {
			protected boolean isScreenEnabled(IScreen screen) {
				return true;
			}
		};
		screenHandler.addScreenListener(new IScreenListener() {

			public void done(IScreen screen) {
				if (parent.isDisposed()) {
					return;
				}
				if (screenToggler.isLast()) {
					fireScreenDone();
				} else {
					screenToggler.nextScreen();
				}
			}
		});
		return screenToggler;
	}

	abstract protected IScreen createPictureScreen(Composite parent,
			ImageDescriptor descriptor);

	public void disposeControl() {
		removeKeyListener(itsDisplay);
		itsScreenToggler.dispose();
	}

	public void setFocus() {
	}

	public void dispose() {
	}

	public IScreen getCurrentScreen() {
		return itsScreenToggler.getActiveScreen();
	}
}
